import services from '@/services/nginx';
import {ActionType, PageContainer, ProColumns, ProTable,} from '@ant-design/pro-components';
import {Button, Divider, message, Modal} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import CreateForm from './components/CreateForm';
import {useNavigate} from '@umijs/max';

const { clouds, page, deleteByAccessId,  append} = services.CloudAccessKeyController;

/**
 * 新增 Access
 * @param fields
 */
const handleAdd = async (fields: API.CloudAccessKeyAdd) => {
  const hide = message.loading('正在添加');
  try {
    await append({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    // message.error('添加失败请重试！');
    return false;
  }
};


/**
 *  删除access
 * @param accessId
 */
const handleRemove = async (accessId: string) => {
  const hide = message.loading('正在删除');
  try {
    await deleteByAccessId(accessId);
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    return false;
  }
};


const TableList: React.FC<unknown> = () => {
  const navigate = useNavigate();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [dictTypeEnumData, setDictTypeEnumData] = useState<Record<string, { text: string; status: string }>>({});
  const [current, setCurrent] = useState(1); // 当前页码
  const [pageSize, setPageSize] = useState(10); // 每页显示条数


  // 字典类型枚举数据
  useEffect(() => {
    async function fetchValueEnumData() {
      const response = await clouds();
      if (response && Array.isArray(response.data)) {
        const dictData = response.data;
        const valueEnumMap: Record<string, { text: string; status: string }> = {};
         // 将字典数据转换为valueEnum格式
        dictData.reduce((acc: { [x: string]: { text: any; status: any; }; }, item: { cloud: string; name: string; }) => {
          acc[item.cloud] =  { text: item.name , status: item.cloud };
          return acc;
        }, valueEnumMap);
        setDictTypeEnumData(valueEnumMap);
      }
    }
    fetchValueEnumData();
  }, []);


  const columns: ProColumns<API.CloudAccessKey>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      tooltip: '唯一的 key',
      hideInForm: true,
      hideInTable: true,
      search: false
    },
    {
      title: '数据名',
      dataIndex: 'name',
      valueType: 'text',
      tooltip: '其他地方显示用的',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '数据名为必填项',
          },
        ],
      },
    },
    {
      title: '账号',
      dataIndex: 'account',
      valueType: 'text',
      copyable: true, // 启用可复制功能
      ellipsis: true, // 启用文本省略
      search: false,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '账号为必填项',
          },
        ],
      },
    },
    {
      title: '账号ID',
      dataIndex: 'accessId',
      valueType: 'text',
      search: false,
      copyable: true, // 启用可复制功能
      ellipsis: true, // 启用文本省略
      formItemProps: {
        rules: [
          {
            required: true,
            message: '账号ID为必填项',
          },
        ],
      },
    },
    {
      title: '账号Secret',
      dataIndex: 'accessSecret',
      valueType: 'password',
      search: false,
      copyable: true, // 启用可复制功能
      formItemProps: {
        rules: [
          {
            required: true,
            message: '账号Secret为必填项',
          },
        ],
      },
    },
    {
      title: '云厂商',
      dataIndex: 'cloud',
      valueEnum: dictTypeEnumData,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '云厂商类型为必填项',
          },
        ],
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'text',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
              onClick={() => {
              Modal.confirm({
                  title: '确认删除',
                  content: '确定要删除吗？',
                  okText: '确认',
                  okType: 'danger',
                  cancelText: '取消',
                  onOk: async () => {
                  const success = await handleRemove(record.accessId);
                    if (success) {
                        actionRef.current?.reloadAndRest?.();
                    }
                  },
              });
              }}
          >
              删除
          </a>
           <Divider type="vertical" />
          <a
              onClick={() => {
                const params = new URLSearchParams({
                  name: record.name,
                });
                const url = `/nginx/cloudAccess/dp/${record.accessId}?${params.toString()}`;
                console.log('Navigating to:', url);
                navigate(url);
              }}
          >
              域名解析
          </a>
        </>
      ),
    },
  ];

  return (
    <PageContainer
      header={{
        title: 'Access',
      }}
    >
      <ProTable
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => handleModalVisible(true)}
          >
            新增
          </Button>,
        ]}
        pagination={{
          current, // 当前页码
          pageSize, // 每页条数
          showSizeChanger: true, // 是否可以改变 pageSize
          pageSizeOptions: ['5', '10', '20', '50'], // 自定义每页条数下拉选项
          onChange: (page, pageSize) => { // 页码或 pageSize 改变的回调。
            setCurrent(page);
            setPageSize(pageSize);
          },
          onShowSizeChange: (current, size) => {// pageSize 改变的回调。
            setCurrent(current);
            setPageSize(size);
          },
        }}
        request={async (params) => {
          const find: API.CloudAccessKeyPage  = {
            cloud: params.cloud,
            name: params.name,
            page : {
              pageIndex: params.current,
              pageSize: params.pageSize,
            },
          };
          const { data, success } = await page({
            ... find,
            // FIXME: remove @ts-ignore
            // @ts-ignore
            // sorter,
            // filter,
          });
          return {
            data: data?.rows || [],
            total: data?.total,
            pageSize: data?.pageSize,
            current: data?.currentPage,
            success,
          };
        }}
        columns={columns}
      />
      <CreateForm
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      >
        <ProTable<API.CloudAccessKey, API.CloudAccessKeyAdd>
          onSubmit={async (value) => {
            const success = await handleAdd(value);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          type="form"
          columns={columns}
        />
      </CreateForm>

    </PageContainer>
  );
};

export default TableList;
